package ru.brostudios.cosmicdonutlivewallpapers;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;

public class CosmicDonut {
	
	private Context context;
	private final int STARS_COUNT = 100;
	private final float STARS_SCALE = 0.03f;
	private final int DONUTS_COEFFICIENT = 2;
	private final float DONUTS_SCALE = 0.28f;
	private List<Star> stars;
	private List<Donut> donuts;
	
	public CosmicDonut(Context context, GL10 gl, int width, int height) {
		this.context = context;
		gl.glClearColor(0.02f, 0.02f, 0.02f, 1.0f);
		stars = new ArrayList<>();
		donuts = new ArrayList<>();
		Resume(gl, width, height);
	}
	
	public void Draw(GL10 gl) {
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		for(int i=0; i<STARS_COUNT; i++) {
			stars.get(i).Draw(gl);
			stars.get(i).Update();
		}
		for(int i=0; i<donuts.size(); i++) {
			donuts.get(i).Draw(gl);
			donuts.get(i).Update();
		}
	}

	public void Pause() {}
	
	public void Resume(GL10 gl, int width, int height) {
		stars.clear();
		Texture starTexture = new Texture(context.getAssets(), "star.png", gl);
		Random rnd = new Random();
		for(int i=0; i<STARS_COUNT; i++) {
			float scale = STARS_SCALE;
			if(width <= height) {
				if(starTexture.width >= starTexture.height) scale = scale*width/starTexture.width;
				else scale = scale*width/starTexture.height;
			}
			else {
				if(starTexture.width >= starTexture.height) scale = scale*height/starTexture.width;
				else scale = scale*height/starTexture.height;
			}
			stars.add(new Star(starTexture, width, height, scale));
		}

		donuts.clear();
		Texture donutsTextures[] = {
			new Texture(context.getAssets(), "donut1.png", gl),
			new Texture(context.getAssets(), "donut2.png", gl),
			new Texture(context.getAssets(), "donut3.png", gl),
			new Texture(context.getAssets(), "donut4.png", gl),
			new Texture(context.getAssets(), "donut5.png", gl),
			new Texture(context.getAssets(), "donut6.png", gl)
		};
		for(int i=0; i<donutsTextures.length*DONUTS_COEFFICIENT; i++) {
			Texture texture = donutsTextures[i%donutsTextures.length];
			float scale = DONUTS_SCALE;
			if(width <= height) {
				if(texture.width >= texture.height) scale = scale*width/texture.width;
				else scale = scale*width/texture.height;
			}
			else {
				if(texture.width >= texture.height) scale = scale*height/texture.width;
				else scale = scale*height/texture.height;
			}
			int w = (width - (int)(texture.width*scale));
			int h = (height - (int)(texture.height*scale));
			int x;
			if(w > 0) x = rnd.nextInt(w) - w/2;
			else x = 0;
			int y;
			if(h > 0) y = rnd.nextInt(h) - h/2;
			else y = 0;
			donuts.add(new Donut(texture, x, y, scale, width, height));
		}
	}
	
}